package com.hymall.realm;

import com.hymall.bean.MarketAdmin;
import com.hymall.bean.MarketAdminExample;
import com.hymall.bean.MarketUser;
import com.hymall.bean.MarketUserExample;
import com.hymall.mapper.MarketAdminMapper;
import com.hymall.mapper.MarketPermissionMapper;
import com.hymall.mapper.MarketUserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * @author: 叶熠彬
 * @description: 自定义realm
 * @date: 2022/7/18 17:36
 */
//需要注册为组件
@Component
public class MallRealm extends AuthorizingRealm {

    @Autowired
    MarketAdminMapper adminMapper;

    @Autowired
    MarketUserMapper userMapper;

    @Autowired
    MarketPermissionMapper permissionMapper;

    //通常把doGetAuthenticationInfo方法放在上面

    //该方法的形参 → 来源于subject的login方法
    // 传入该值，为了根据用户名查询到该用户在系统中的密码（数据库中维护） → 来构造认证信息

    /**
     * 进行验证
     *
     * @author: 叶熠彬
     * @date: 2022/7/18 17:58
     * @param: [authenticationToken]
     * @return: org.apache.shiro.authc.AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MarketToken marketToken = (MarketToken) authenticationToken;
        //根据AuthenticationToken中的用户名信息查询数据库中的信息
        //Principal表示携带的信息
        String username = (String) authenticationToken.getPrincipal();
        String type = marketToken.getType();
        if ("admin".equals(type)) {
            MarketAdminExample adminExample = new MarketAdminExample();
            adminExample.createCriteria().andUsernameEqualTo(username);
            List<MarketAdmin> marketAdmins = adminMapper.selectByExample(adminExample);
            if (marketAdmins.size() == 1) {
                MarketAdmin admin = marketAdmins.get(0);
                //返回一个AuthenticationToken对象（构造认证信息）
                // 第一个参数是principal放入的信息
                //第二个参数credentials，是真实（正确）的密码，会和AuthenticationToken中的password做比较
                //第三个是realm的name，没用但是要写
                return new SimpleAuthenticationInfo(admin, admin.getPassword(), getName());
            }
            return null;
        }
        if ("wx".equals(type)) {
            MarketUserExample marketUserExample = new MarketUserExample();
            marketUserExample.createCriteria().andUsernameEqualTo(username);
            List<MarketUser> marketUsers = userMapper.selectByExample(marketUserExample);
            if (marketUsers.size()==1){
                MarketUser user = marketUsers.get(0);
                return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
            }
        }
        return null;
    }

    /**
     * 进行授权
     *
     * @author: 叶熠彬
     * @date: 2022/7/18 19:33
     * @param: [principalCollection]
     * @return: org.apache.shiro.authz.AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 根据用户信息拿到所有的权限（数据库）
        // doGetAuthenticationInfo方法返回值的第一个参数就是用户信息
        // 放入的是MarketAdmin类型的Principal信息，取出MarketAdmin
        MarketAdmin admin = (MarketAdmin) principalCollection.getPrimaryPrincipal();
        //根据admin查询角色id，获得权限
        Integer[] adminRoleIds = admin.getRoleIds();
        List<String> permissions = permissionMapper.selectPermissionsByAdminRoleIds(adminRoleIds);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }


}
